package com.cloudfast.common.result;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.util.MultiValueMap;

import com.cloudfast.context.error.ErrorCode;

import lombok.Getter;
import lombok.Setter;

/**
 * ajax 请求返回类
 *
 * @author liuyw
 */
@SuppressWarnings("serial")
@Setter
@Getter
public final class ApiResponse extends ResponseEntity<Object> implements Serializable {

    private HttpStatus httpStatus;

    private ApiResponse(Object body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
        super(body, headers, status);
        setHttpStatus(status);
    }

    public static ApiResponse message(ErrorCode errorCode) {
        Map<String, Object> map = new HashMap<>();
        map.put("msg", errorCode.getMsg());
        map.put("code", errorCode.getCode());
        return new ApiResponse(map, initHeader(), errorCode.getHttpStatus());
    }

    public static ApiResponse success(Object data) {

        return new ApiResponse(initMap(data), initHeader(), HttpStatus.OK);
    }

    public static ApiResponse blob(byte[] bytes) {
        return new ApiResponse(bytes, initHeader(), HttpStatus.OK);
    }

    private static MultiValueMap<String, String> initHeader() {
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-Security-Policy", "default-src 'none';");
        return headers;
    }

    private static Map<String, Object> initMap(Object data) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("data", data);
        map.put("success", true);
        return map;
    }

    public static ApiResponse error(String msg) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", -1);
        map.put("msg", msg);
        map.put("success", false);
        return new ApiResponse(map, initHeader(), HttpStatus.OK);
    }
}
